<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Http\Models\Rank;
use App\Http\Models\Item;
use App\Http\Models\Record;

class RankController extends Controller
{
    public function __construct()
    {

    }

    /**
     * 本周排行榜
     *
     * @param Request $req
     * @return void
     */
    public function lists(Request $req)
    {
        // type 1:本周 2:上周
        $type = $req->input('type', 1);
        $page = $req->input('page');
        if (!$page) return $this->throwError('ErrClientParams');

        $uid = \Auth::user();
        if (!$uid) return $this->throwError('ErrUnAuthorization');
        $uinfo = DB::table('users')->where('id', $uid)->first();
        if(!isset($uinfo['id'])) return $this->throwError('ErrGetUser');

        // 计算条数
        $page--;
        $page_num = 99;
        $start = $page * $page_num;
        $end = $start + $page_num;
        // 区分本周还是上周
        $type = $type==1 ? 'DW' : 'LW';
        if($type == 'DW') {
            $lists = Rank::gets( $start, $end );
        } else {
            $lists = Rank::gets( $start, $end, true );
        }
        // 查询数据
        $result_lists = [];
        if( !empty( $lists ) ) {
            $rank = $start + 1;
            foreach( $lists as $u_id => $score ) {
                $u_info = DB::table('users')->where('id', $u_id)->first();
                if( !isset($u_info['duckId']) ) continue;
                $result_lists[] = [
                    'rank' => $rank++,
                    'nick_name' => $u_info['nickName'] ?? '',
                    'avatar' => $u_info['avatar'] ?? '',
                    'active' => $score ?? 0,
                ];
            }
        }

        return $this->result([
            'list' => $result_lists
        ]);
    }

    /**
     * 获取排行榜界面banner和自己的排名数据
     */
    public function rankOneself(Request $req)
    {
        $uid = \Auth::user();
        if (!$uid) return $this->throwError('ErrUnAuthorization');
        $uinfo = DB::table('users')->where('id', $uid)->first();
        if(!isset($uinfo['id'])) return $this->throwError('ErrGetUser');

        $oneself = Rank::getOne( $uid );
        $oneselfLW = Rank::getOne( $uid, true );

        $active_rank_banner = DB::table('active_rank')->where('id', 1)->first();
        $active_rank_color = DB::table('active_rank')->where('id', 4)->first();
        $active_rank_strategy = DB::table('active_rank')->where('id', 5)->first();
        $result_strategy = [];
        if(!empty($active_rank_strategy) && !empty($active_rank_strategy['val'])) {
            $result_strategy = json_decode( $active_rank_strategy['val'], true );
            ksort($result_strategy);
        }

        return $this->result([
            'banner' => $active_rank_banner['val'] ?? '',
            'color' => $active_rank_color['val'] ?? '',
            'strategy' => $result_strategy ?? [],
            'oneself' => [
                'rank' => $oneself['index'] ?? 0,
                'nick_name' => $uinfo['nickName'] ?? '',
                'avatar' => $uinfo['avatar'] ?? '',
                'active' => $oneself['score'] ?? 0,
            ],
            'oneselfLW' => [
                'rank' => $oneselfLW['index'] ?? 0,
                'nick_name' => $uinfo['nickName'] ?? '',
                'avatar' => $uinfo['avatar'] ?? '',
                'active' => $oneselfLW['score'] ?? 0,
            ],
        ]);
    }

    /**
     * 领取上周的排行榜奖励
     */
    public function receiveRankReward(Request $req)
    {
        $uid = \Auth::user();
        if (!$uid) return $this->throwError('ErrUnAuthorization');
        $uinfo = DB::table('users')->where('id', $uid)->first();
        if(!isset($uinfo['id'])) return $this->throwError('ErrGetUser');
        // 查询自己上周的名次
        $oneselfLW = Rank::getOne( $uid, true );
        // $oneselfLW['index'] = 1;
        // 根据名次查询自己是否有奖励可以领取
        if(!$oneselfLW['index']) return $this->result();
        // 查询自己奖励有没有领取过
        $config = DB::table('active_rank')->where('id', 3)->first();
        if(empty($config) || empty($config['val'])) $config['val'] = 0;
        if($uinfo['ar_period'] >= $config['val']) return $this->result();

        $config_reward = DB::table('active_rank')->where('id', 2)->first();
        if(empty($config_reward) || empty($config_reward['val'])) return $this->result();
        $reward = json_decode($config_reward['val'], true);
        if(!isset($reward[$oneselfLW['index']])) return $this->result();

        // 发放奖励
        $rewards = Item::give($uid, $reward[$oneselfLW['index']]['reward'], $uinfo, 'active_rank');
        // 更改自己的状态为奖励已领取
        DB::table('users')->where('id', $uid)->update([
            'ar_period' => $config['val']
        ]);

        // 动态记录
        if($rewards) {
            $add_star = 0;
            foreach($reward[$oneselfLW['index']]['reward'] as $info) {
                if($info['type'] == config('game.cfg.ItemTypeStar')) {
                    $add_star += $info['num'];
                }
            }
            if($add_star > 0)
            Record::new(
                $uid,
                config('game.cfg.BaseRecordTypeNormal'),
                config('game.cfg.BaseRecordActiveRankReward'),
                [$add_star]
            );
        }

        return $this->result([
            'reward' => $rewards,
            'rank' => $oneselfLW['index'],
        ]);
    }
}
